<template>
  <div class="alarm-container">
    <div class="header">
      <h2>报警记录</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属家庭">
          <el-select 
            v-model="searchForm.family_id" 
            placeholder="请选择家庭"
            clearable
            @change="handleFamilyChange"
            @clear="handleFamilyClear"
            class="search-select"
          >
            <el-option
              v-for="item in familyList"
              :key="item.family_id"
              :label="item.family_name"
              :value="item.family_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检测地点">
          <el-select 
            v-model="searchForm.site_id" 
            placeholder="请选择检测地点"
            clearable
            @clear="handleSearch"
            :disabled="!searchForm.family_id"
            class="search-select"
          >
            <el-option
              v-for="item in filteredSiteList"
              :key="item.site_id"
              :label="getLocationName(item)"
              :value="item.site_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报警类型">
          <el-select 
            v-model="searchForm.alert_type" 
            placeholder="请选择报警类型"
            clearable
            @clear="handleSearch"
            class="search-select"
          >
            <el-option label="PM2.5超标" value="pm25" />
            <el-option label="PM10超标" value="pm10" />
            <el-option label="温度异常" value="temperature" />
            <el-option label="湿度异常" value="humidity" />
            <el-option label="甲醛超标" value="formaldehyde" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择状态"
            clearable
            @clear="handleSearch"
            class="search-select"
          >
            <el-option label="待处理" value="pending" />
            <el-option label="已处理" value="processed" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="alarmList" style="width: 100%" v-loading="loading" border stripe>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column label="检测地点" min-width="180" align="center">
        <template #default="{ row }">
          {{ getLocationName(getSiteInfo(row.site_id)) }}
        </template>
      </el-table-column>
      <el-table-column label="报警类型" align="center">
        <template #default="{ row }">
          <el-tag :type="getAlertTypeTag(row.alert_type)">
            {{ getAlertTypeName(row.alert_type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报警值" align="center">
        <template #default="{ row }">
          <span :class="getAlertValueClass(row)">
            {{ row.alert_value.toFixed(2) }} {{ getUnit(row.alert_type) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="alert_time" label="报警时间" width="180" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 'pending' ? 'danger' : 'success'">
            {{ row.status === 'pending' ? '待处理' : '已处理' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getAlarmList, getAlarmBySiteId } from '@/api/alarm'
import { getFamilyList } from '@/api/family'
import { getSiteList } from '@/api/site'
import { getRoomList } from '@/api/room'

// 数据列表
const alarmList = ref([])
const familyList = ref([])
const siteList = ref([])
const roomList = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  family_id: '',
  site_id: '',
  alert_type: '',
  status: ''
})

// 根据选择的家庭过滤传感器列表
const filteredSiteList = computed(() => {
  if (!searchForm.value.family_id) return []
  return siteList.value.filter(site => {
    const room = roomList.value.find(room => room.room_id === site.room_id)
    return room && room.family_id === searchForm.value.family_id
  })
})

// 获取位置名称
const getLocationName = (site) => {
  if (!site) return '未知位置'
  const room = roomList.value.find(r => r.room_id === site.room_id)
  if (!room) return `未知房间-${site.site_name}`
  const family = familyList.value.find(f => f.family_id === room.family_id)
  if (!family) return `未知家庭-${room.room_name}-${site.site_name}`
  return `${family.family_name}-${room.room_name}-${site.site_name}`
}

// 获取传感器信息
const getSiteInfo = (siteId) => {
  return siteList.value.find(s => s.site_id === siteId)
}

// 获取报警类型名称
const getAlertTypeName = (type) => {
  const types = {
    pm25: 'PM2.5超标',
    pm10: 'PM10超标',
    temperature: '温度异常',
    humidity: '湿度异常',
    formaldehyde: '甲醛超标'
  }
  return types[type] || type
}

// 获取报警类型标签样式
const getAlertTypeTag = (type) => {
  const types = {
    pm25: 'danger',
    pm10: 'danger',
    temperature: 'warning',
    humidity: 'warning',
    formaldehyde: 'danger'
  }
  return types[type] || 'info'
}

// 获取单位
const getUnit = (type) => {
  const units = {
    pm25: 'μg/m³',
    pm10: 'μg/m³',
    temperature: '°C',
    humidity: '%',
    formaldehyde: 'mg/m³'
  }
  return units[type] || ''
}

// 获取报警值样式
const getAlertValueClass = (row) => {
  return {
    'alert-value': true,
    'alert-danger': row.status === 'pending'
  }
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    let res
    if (searchForm.value.site_id) {
      res = await getAlarmBySiteId(searchForm.value.site_id)
    } else {
      res = await getAlarmList()
    }
    
    // 过滤数据
    let filteredData = res.data
    
    if (searchForm.value.alert_type) {
      filteredData = filteredData.filter(item => 
        item.alert_type === searchForm.value.alert_type
      )
    }
    
    if (searchForm.value.status) {
      filteredData = filteredData.filter(item => 
        item.status === searchForm.value.status
      )
    }
    
    alarmList.value = filteredData
  } catch (error) {
    console.error('获取报警记录失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理家庭选择变化
const handleFamilyChange = () => {
  searchForm.value.site_id = ''
  handleSearch()
}

// 处理家庭清空
const handleFamilyClear = () => {
  searchForm.value.site_id = ''
  handleSearch()
}

// 查询按钮点击
const handleSearch = () => {
  getList()
}

// 重置按钮点击
const handleReset = () => {
  searchForm.value = {
    family_id: '',
    site_id: '',
    alert_type: '',
    status: ''
  }
  getList()
}

// 初始化数据
const initData = async () => {
  try {
    const [familyRes, roomRes, siteRes] = await Promise.all([
      getFamilyList(),
      getRoomList(),
      getSiteList()
    ])
    
    familyList.value = familyRes.data
    roomList.value = roomRes.data
    siteList.value = siteRes.data
    
    await getList()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.alarm-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 调整表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 15px;
  margin-right: 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 统一下拉选择框宽度和样式 */
:deep(.search-select) {
  width: 200px;
}

:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

/* 按钮组样式 */
.search-buttons {
  margin-left: auto;
}

/* 报警值样式 */
.alert-value {
  font-weight: bold;
}

.alert-danger {
  color: #F56C6C;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}
</style> 